package com.food.service.impl;

import com.food.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class EmailServiceImpl implements EmailService {

    private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendVerificationCode(String to, String code) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject("验证码");
            message.setText("您的验证码是: " + code + "\n验证码有效期为5分钟。");
            mailSender.send(message);
        } catch (MailException e) {
            logger.error("Failed to send verification code email", e);
            throw new RuntimeException("发送验证码邮件失败", e);
        }
    }

    @Override
    public void sendPasswordResetLink(String to, String token) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject("重置密码");
            message.setText("请点击以下链接重置密码：\nhttp://localhost:8080/reset-password?token=" + token);
            mailSender.send(message);
        } catch (MailException e) {
            logger.error("Failed to send password reset email", e);
            throw new RuntimeException("发送重置密码邮件失败", e);
        }
    }

    @Override
    public void sendWelcomeEmail(String to, String username) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject("欢迎注册");
            message.setText("尊敬的 " + username + "，欢迎使用我们的膳食推荐系统！");
            mailSender.send(message);
        } catch (MailException e) {
            logger.error("Failed to send welcome email", e);
            throw new RuntimeException("发送欢迎邮件失败", e);
        }
    }
} 